var express = require('express');
const NewsController = require('../../controllers/admin/NewsController');
const JWT = require('../../util/JWT');
const path = require('path');
const UserService  = require('../../services/admin/UserService')
var router = express.Router();
const multer  = require('multer')
const storage = multer.diskStorage({
    destination: (req, file, cb) => {
      cb(null, __dirname+'/../../public/newsavator'); // 指定文件保存的目录
    },
    filename: (req, file, cb) => {
      // 保留原始的文件扩展名
      const ext = path.extname(file.originalname);
      cb(null, file.fieldname + '-' + Date.now() + ext);
    },
  });
  const upload = multer({ storage: storage })
  
router.use(
    (req, res, next) => {
       let token= req.get('token')
       let data=JWT.verify(token);
        if (req.path === '/user/login') {
            next();
            return;
        }
        if (JWT.verify(token)===false) {
            res.send({
                code: 400,
                msg: '登入已过期'
            });
        } else {
            res.header('token',JWT.generate({result:data.result},'1h'))
            next();
        }
    }
);

router.post('/newsadd', upload.single('file'),NewsController.AddNews)
router.post('/getallnews', upload.single('file'),NewsController.GetAllNews)
router.post('/isPublish',NewsController.isPublish)
router.post('/newdelete',NewsController.Newdelete)
router.post('/newEdit',upload.single('file'),NewsController.NewEdit)


module.exports = router;